//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

declare var $;
declare var GLOBAL_PATH;
declare var getQueryString;
declare var USER_ID;
declare var STAGE;
declare var HAS_OLD_SCORE;
declare var SCORE;
declare var CANREAD;
declare var SHOWRESULT;
declare var QSID;
declare var AVATOR;


class Main extends eui.UILayer {

    private musicTime;

    protected createChildren(): void {
        super.createChildren();

        egret.lifecycle.addLifecycleListener((context) => {
            // custom lifecycle plugin
        })

        egret.lifecycle.onPause = () => {
            egret.ticker.pause();

            if(GLOBAL_CHANNEL) {
                this.musicTime = GLOBAL_CHANNEL.position;
                GLOBAL_CHANNEL.stop();
            }
        }

        egret.lifecycle.onResume = () => {
            egret.ticker.resume();
            if(GLOBAL_CHANNEL) {
                GLOBAL_CHANNEL = GLOBAL_MUSIC.play(this.musicTime,1);
            }
        }

        //inject the custom material parser
        //注入自定义的素材解析器
        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());


        this.runGame().catch(e => {
            console.log(e);
        })
    }

    private async runGame() {
        await this.loadResource()
        const result = await RES.getResAsync("description_json")
        this.createGameScene();
    }

    private async loadResource() {
        try {
            const loadingView = new LoadingUI();
            this.stage.addChild(loadingView);
            await RES.loadConfig("resource/default.res.json", "resource/");
            await this.loadTheme();
            await RES.loadGroup("preload", 0, loadingView);
            this.stage.removeChild(loadingView);
        }
        catch (e) {
            console.error(e);
        }
    }

    private loadTheme() {
        return new Promise((resolve, reject) => {
            // load skin theme configuration file, you can manually modify the file. And replace the default skin.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            let theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);

        })
    }

    private textfield: egret.TextField;
    /**
     * 创建场景界面
     * Create scene interface
     */
    protected createGameScene(): void {
        $.ajax({
            url: GLOBAL_PATH + '/question/user/share',
            method:'POST',
            headers: {
                'Content-Type': "application/json;charset=UTF-8"
            },
            data: JSON.stringify({code: getQueryString('code'),url: window.location.href.split('#')[0]}),
            success:(res) => {
                if(!JSON.parse(res).success) return
                res = JSON.parse(res)
                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: 'wxeac125aaacee378d', // 必填，公众号的唯一标识
                    timestamp: res.data.timestamp, // 必填，生成签名的时间戳
                    nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
                    signature: res.data.signature,// 必填，签名
                    jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage'] // 必填，需要使用的JS接口列表
                });

                wx.ready(function(){
                    wx.onMenuShareAppMessage({
                        title: '测测孩子的5种思维力', // 分享标题
                        desc: '我的孩子竟然有这种天赋', // 分享描述
                        link: 'https://xcx.mifengshuxue.com/question/assets/v1/index.html', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'http://xcx.mifengshuxue.com/question/assets/v1/resource/image/shareImg.png', // 分享图标
                        success: function () {
                            SHOWRESULT();
                        }
                    });

                    wx.onMenuShareTimeline({
                        title: '测测孩子的5种思维力', // 分享标题
                        link: 'https://xcx.mifengshuxue.com/question/assets/v1/index.html', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'http://xcx.mifengshuxue.com/question/assets/v1/resource/image/shareImg.png', // 分享图标
                        success: function () {
                            SHOWRESULT();
                        }
                    })
                });
            }
        })
        $.ajax({
            url: GLOBAL_PATH + '/question/user/login',
            method:'POST',
            headers: {
                'Content-Type': "application/json;charset=UTF-8"
            },
            data: JSON.stringify({code: getQueryString('code')}),
            success:(res) => {
                $('.loading-shadow').hide();
                $('.loading').hide();
                let data = JSON.parse(res).data;
                if(JSON.parse(res).success){
                    AVATOR = data.headImgUrl;
                    HAS_OLD_SCORE = (data.math === 0 || data.math) ? true : false;
                    if(HAS_OLD_SCORE) {
                        SCORE = {
                            math: data.math,    //数感
                            illation: data.illation,    //推理
                            observation: data.observation, //观察
                            space: data.space,   //空间感
                            memory: data.memory   //记忆力
                        }
                    }
                    QSID = data.reportId || '';
                    CANREAD = data.shareStatus === 1 || data.payStatus === 1;
                    USER_ID = data.userId;
                }
                let background = this.createBitmapByName('startBg_png');
                background.width = this.stage.stageWidth;
                background.height = this.stage.stageHeight - 296;
                background.x = 0;
                background.y = 296;

                var yellowBg:egret.Shape = new egret.Shape();
                yellowBg.graphics.beginFill(0xeed480);
                yellowBg.graphics.drawRoundRect(0, 0, this.stage.stageWidth, this.stage.stageHeight, 0, 0);
                
                yellowBg.graphics.endFill();
                this.addChild(yellowBg);

                let bottom = this.createBitmapByName('bottom_png');
                bottom.width = this.stage.stageWidth;
                bottom.height = 85;
                bottom.x = 0;
                bottom.y = this.stage.stageHeight - bottom.height;
                this.addChild(background);
                this.addChild(bottom);
                this.addChild(SceneMange.getInstance(this.stage.stageHeight, this.stage.stageWidth));
            }
        })
    }
    /**
     * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
     * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
     */
    private createBitmapByName(name: string): eui.Image {
        let result = new eui.Image();
        let texture: egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;
    }


}
